package com.gouying.web.service.impl;

import com.gouying.common.constant.WareConstant;
import com.gouying.common.utils.PageUtils;
import com.gouying.common.utils.Query;
import com.gouying.web.dao.PurchaseDao;
import com.gouying.web.entity.PurchaseDetailEntity;
import com.gouying.web.entity.PurchaseEntity;
import com.gouying.web.service.PurchaseDetailService;
import com.gouying.web.service.PurchaseService;
import com.gouying.web.service.WareSkuService;
import com.gouying.web.vo.MergeVo;
import com.gouying.web.vo.PurchaseDoneVo;
import com.gouying.web.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.springframework.transaction.annotation.Transactional;

@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService detailService;

    @Autowired
    WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceiveList(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                //查询的是新建和已分配状态下的采购单
                new QueryWrapper<PurchaseEntity>().eq("status",0).or().eq("status",1)
        );
        return new PageUtils(page);
    }

    //合并采购单
    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        //如果要合并到的采购单id为空，则创建新的采购单
        if (purchaseId == null) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            //设置几个默认属性
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            //
            purchaseId = purchaseEntity.getId();
        }

        //TODO 确认采购单状态是0,1才可以进行合并

        List<Long> items = mergeVo.getItems();
        //最终整合成的采购单id
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> collect = items.stream().map(i->{
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();

            detailEntity.setId(i);
            detailEntity.setPurchaseId(finalPurchaseId);
            detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return detailEntity;
        }).collect(Collectors.toList());
        detailService.updateBatchById(collect);

        //合并采购单之后同时更新时间
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

    //领取采购单的方法
    @Override
    public void received(List<Long> ids) {
        //1、确认当前采购单是新建或者已分配状态
        List<PurchaseEntity> collect = ids.stream().map(id -> {
            //根据采购单id得到采购需求的详细信息
            PurchaseEntity byId = this.getById(id);
            return byId;
            //对得到的采购单进行过滤，得到当前采购需求是新建或者已分配状态的
        }).filter(item -> {
            //采购单状态码为新建或者已分配状态的
            if (item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
                    item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                //返回这些符合要求的采购单
                return true;
            }
            //否则不符合要求
            return false;
        }).map(item->{
            //将采购单状态修改为已领取
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            //同时设置修改时间
            item.setUpdateTime(new Date());
            return item;
        }).collect(Collectors.toList());
        //2、批量改变所有采购单的状态
        this.updateBatchById(collect);
        //3、改变所有采购单中采购项信息
        //遍历每个采购单的信息
        collect.forEach(item->{
            List<PurchaseDetailEntity> entities = detailService.listDetailByPurchaseId(item.getId());
            //根据主键批量更新
            List<PurchaseDetailEntity> detailEntities = entities.stream().map(entity -> {
                //只更新状态即可
                PurchaseDetailEntity entity1 = new PurchaseDetailEntity();
                //设置采购单id
                entity1.setId(entity.getId());
                //将状态修改为“正在采购”
                entity1.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return entity1;
            }).collect(Collectors.toList());
            detailService.updateBatchById(detailEntities);
        });
    }

    //采购完成进行提交
    @Transactional
    @Override
    public void done(PurchaseDoneVo doneVo) {
        //提取传递过来的采购单id
        Long id = doneVo.getId();

        //1、改变采购项的状态
        //是否全部成功标识
        Boolean flag = true;
        List<PurchaseItemDoneVo> items = doneVo.getItems();
        //保存
        List<PurchaseDetailEntity> updates = new ArrayList<>();
        //对采购项进行遍历
        for (PurchaseItemDoneVo item : items) {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            //如果有失败的采购项
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
                //则不能全部成功
                flag = false;
                //保存失败采购项的状态
                detailEntity.setStatus(item.getStatus());
            } else {
                //否则则设置采购项状态为已完成
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                //3、将成功采购的商品进行入库
                //根据id查出当前采购项
                PurchaseDetailEntity entity = detailService.getById(item.getItemId());
                //设置该采购项的各个参数
                wareSkuService.addStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum());
            }
            //设置这个采购项的id
            detailEntity.setId(item.getItemId());
            //添加各个采购项
            updates.add(detailEntity);
        }
        //更新采购项
        detailService.updateBatchById(updates);

        //2、改变采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        //设置采购单id
        purchaseEntity.setId(id);
        //如果采购项表示不为true（有失败项），则设置有异常；否则为已完成
        purchaseEntity.setStatus(flag? WareConstant.PurchaseStatusEnum.FINISH.getCode():WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        //更新采购单
        this.updateById(purchaseEntity);


    }

}